package org.kiwi.data.util;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.Assert;

/**
 * Created by jack on 16/12/17.
 */
public class SPELUtil {

    public static Object getValue(String[] paramNames,
                                  Object[] args,
                                  String expression,
                                  BeanFactory beanFactory) {
        Assert.hasText(expression, "expression is required");

        ExpressionParser expressionParser = new SpelExpressionParser();

        StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
        if (beanFactory != null) {
            evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory));
        }

        if (!ArrayUtils.isEmpty(paramNames) && !ArrayUtils.isEmpty(args)) {
            if (paramNames.length != args.length) {
                throw new IllegalArgumentException("args length must be equals to paraNames length");
            }
            for (int i = 0; i < paramNames.length; i++) {
                evaluationContext.setVariable(paramNames[i], args[i]);
            }
        }

        return expressionParser.parseExpression(expression).getValue(evaluationContext);
    }
}